package com.haiermzj.client.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RadioGroup;

import com.haiermzj.client.R;
import com.haiermzj.client.fragments.MainFragment;
import com.haiermzj.client.fragments.MeFragment;

public class MainActivity extends AppCompatActivity {

    private RadioGroup bottomRadioGroup;
    private FragmentManager supportFragmentManager;
    private Fragment showFragmnent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); //设置无标题
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);  //设置全屏
        setContentView(R.layout.activity_main);
        initView();
        supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        showFragmnent = new MainFragment();
        fragmentTransaction.add(R.id.fragment_container, showFragmnent, MainFragment.TAG);
        fragmentTransaction.commitAllowingStateLoss();
        bottomRadioGroup.check(1);

    }

    private void initView() {
        /*底部RadioGroup*/
        bottomRadioGroup = (RadioGroup) findViewById(R.id.bottom_radio_group);
        bottomRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case 1:
                        changeFragment(MainFragment.class, MainFragment.TAG);
                        break;
                    case 2:
                        changeFragment(MeFragment.class, MeFragment.TAG);

                        break;
                }
            }
        });
    }

    private void changeFragment(Class<? extends Fragment> cls, String tag) {

        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        fragmentTransaction.hide(showFragmnent);
        showFragmnent = supportFragmentManager.findFragmentByTag(tag);
        if (showFragmnent == null) {
//            未显示过
            try {
                showFragmnent = cls.newInstance();
                fragmentTransaction.add(R.id.fragment_container, showFragmnent, tag);

            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
            fragmentTransaction.show(showFragmnent);
        }
        fragmentTransaction.commitAllowingStateLoss();


    }


}
